﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace IP_PROJECT
{
    public partial class Contact : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void SaveContacts_Click(object sender, EventArgs e)
        {
            DataClassesDataContext db = new DataClassesDataContext();
            var result = from u in db.Maps
                         where u.View == "Contact"
                         select u;
            Dictionary<int, Map> entities = result.ToDictionary(map => map.Id);
            foreach (RepeaterItem item in ContactRepeater.Items)
            {
                LoginView loginView = (LoginView)item.FindControl("UserView");
                TextBox idBox = (TextBox)loginView.FindControl("Id");
                TextBox keyBox = (TextBox)loginView.FindControl("KeyInput");
                TextBox valueBox = (TextBox)loginView.FindControl("ValueInput");
                
                Map entity = entities[int.Parse(idBox.Text)];
                entity.Key = keyBox.Text;
                entity.Value = valueBox.Text;
            }

            TextBox newKey = (TextBox)SaveView.FindControl("KeyInput");
            TextBox newValue = (TextBox)SaveView.FindControl("ValueInput");
            if (newKey.Text.Length > 0 || newValue.Text.Length > 0)
            {
                Map newRecord = new Map();
                newRecord.Key = newKey.Text;
                newRecord.Value = newValue.Text;
                newRecord.View = "Contact";
                db.Maps.InsertOnSubmit(newRecord);
            }

            db.SubmitChanges();
            Response.Redirect(Request.Url.ToString());
        }

        protected void FieldDelete_Click(object sender, EventArgs e)
        {
            String id = ((Button)sender).CommandArgument;
            DataClassesDataContext db = new DataClassesDataContext();
            var result = from u in db.Maps
                         where u.Id == int.Parse(id)
                         select u;
            Map map = result.ToList().First();
            db.Maps.DeleteOnSubmit(map);            
            db.SubmitChanges();
            Response.Redirect(Request.Url.ToString());
        }
    }
}